<template>
  <div id="poster">
    <div class="registe_step">
      <!-- 步骤条 -->
      <el-steps
        :active="step.active"
        align-center="true"
        finish-status="success"
      >
        <el-step :title="step.title1" description="验证邮箱"></el-step>
        <el-step :title="step.title2" description="填写账号"></el-step>
        <el-step :title="step.title3" description="注册成功"></el-step>
      </el-steps>

      <!-- 登陆表单之确认邮箱发送验证码 -->
      <div v-show="stepDivFirst" class="step_first">
        <el-form
          class="registe_container"
          :model="registerForm"
          status-icon
          :rules="registerFormRulesFirst"
          ref="registerFormRefFirst"
        >
          <h3 class="registe_title">欢迎注册</h3>

          <el-form-item prop="email">
            <el-input
              type="text"
              auto-complete="off"
              placeholder="请输入邮箱"
              prefix-icon="el-icon-message"
              v-model="registerForm.email"
            ></el-input>
          </el-form-item>

          <el-form-item prop="code">
            <el-row gutter="24">
              <el-col :span="14">
                <el-input
                  maxlength="8"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  prefix-icon="el-icon-chat-line-square"
                  v-model="registerForm.code"
                ></el-input>
              </el-col>

              <el-col :span="10">
                <el-button
                  type="primary"
                  round
                  block
                  @click="getCode"
                  :loding="dataItem.button_loading"
                  :disabled="dataItem.button_disabled"
                >
                  {{ dataItem.button_get }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <!-- <el-form-item> -->
          <el-button
            round
            type="primary"
            @click="stepNextFirst"
            auto-complete="off"
            class="next_button_first"
            v-loading="loading"
            >下一步</el-button
          >
          <!-- element-loading-text="拼命加载中" -->
          <!-- </el-form-item> -->
        </el-form>
      </div>

      <!-- 登陆表单之设置账号和密码 -->
      <div v-show="stepDivSecond" class="step_second">
        <el-form 
        class="registe_container"
        :model="registerForm"
        status-icon
        :rules="registerFormRulesSecond"
        ref="registerFormRefSecond"
        >

          <h3 class="registe_title">账号信息</h3>

          <el-form-item prop="username">
            <el-input
              type="text"
              auto-complete="off"
              placeholder="请输入账号"
              prefix-icon="el-icon-user"
              v-model="registerForm.username"
            ></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              type="password"
              auto-complete="off"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              v-model="registerForm.password"
            ></el-input>
          </el-form-item>

          <el-form-item prop="passwords">
            <el-input
              type="password"
              auto-complete="off"
              placeholder="请确认密码"
              prefix-icon="el-icon-lock"
               v-model="registerForm.passwords"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              round
              type="primary"
              @click="stepNextSecond"
              auto-complete="off"
              class="next_button_second"
              v-loading="loading"
              >下一步</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- 第三步 -->
      <div v-show="stepDivThird" class="step_third">
        <el-dialog
          title="注册已完成"
          v-model="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <span>是否前往登录页面？</span>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="falseButton">取 消</el-button>
              <el-button type="primary" @click="trueButton">确 定</el-button>
            </span>
          </template>
        </el-dialog>

        <el-button @click="stepNextThird" type="prim"
          >注册完成了，去登陆?</el-button
        >
      </div>

    </div>
  </div>
</template>

<script>
import { checkEmailAndCode, getEmailCode, register } from "../api/interface";
import QS from "qs";
import { h } from "vue";
import router from "../router/index";
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      //邮箱正则，没找到一个靠谱的
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;

      if (!value) {
        return callback(new Error("请输入邮箱"));
      }
      if (!regEmail.test(value)) {
        return callback(new Error("请输入正确的邮箱"));
      }
      if (regEmail.test(value)) {
        return callback();
      }
    };

    const checkCode = (rule, value, callback) => {
      //验证码正则
      const regCode = /^[0-9]{8}$/;
      if (!value) {
        return callback(new Error("请输入验证码"));
      }
      if (!regCode.test(value)) {
        return callback(new Error("验证码为8位数字"));
      }
      if (regCode.test(value)) {
        return callback();
      }
    };

    const checkUsername = (rule, value, callback) => {
      //用户名正则
      const regUsername = /^[a-zA-Z0-9]{8,16}$/;
      if(!value){
        return callback(new Error("请输入账号"))
      }
      if(!regUsername.test(value)){
        return callback(new Error("账号为8-16位数字或字母"))
      }
      if(regUsername.test(value)){
        return callback();
      }
    }

    const checkPassword = (rule, value, callback) => {

      const regPassword = /^[a-zA-Z0-9]{8,20}$/;
      // let password = this.registerForm.password;
      // let passwords = this.registerForm.passwords;
      if(value === ''){
        return callback(new Error("请输入密码"))
      }
      if(!regPassword.test(value)){
        return callback(new Error("密码为8-20位数字或字母"))
      }
      // if(password  && value){
      //   if(passwords !== value){
      //     return callback(new Error("输入的密码不一致"))
      //   }
      // }
      if(regPassword.test(value)){
        return callback();
      }

    }

    const checkPasswords = (rule, value, callback) => {

      const regPasswords = /^[a-zA-Z0-9]{8,20}$/;
      let password = this.registerForm.password;
      let passwords = this.registerForm.passwords;
      if(value === ''){
        return callback(new Error("请输入密码"))
        
      }
      if(!regPasswords.test(value)){
        return callback(new Error("密码为8-20位数字或字母"))
      }
      if(passwords && value){
        if(password !== value){
          return callback(new Error("输入的密码不一致"))
        }
      }
      if(regPasswords.test(value)){
        return callback();
      }
      

    }

    return {
      registerForm: {
        email: "",
        username: "",
        password: "",
        passwords: "",
        code: "",
      },
      
      //第一步验证
      registerFormRulesFirst: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { validator: checkCode, trigger: "blur" },
        ],
      },
      //第二步验证
      registerFormRulesSecond: {
        username: [
          { required: true, message: "请输入账号",trigger: "blur" },
          { validator: checkUsername, trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" }
        ],
        passwords: [
          { required: true, message:"请确认密码", trigger: "blur" },
          { validator: checkPasswords, trigger: "blur" }
        ]
      },
      //步骤条
      step: {
        active: "",
        title1: "",
        title2: "",
        title3: "",
      },
      //隐藏div，对应step步骤条
      stepDivFirst: true,
      stepDivSecond: false,
      stepDivThird: false,
      //对话框的
      dialogVisible: false,
      //加载效果
      loading: false,
      //验证码相关
      dataItem: {
        button_get: "获取验证码",
        button_loading: false,
        button_disabled: false,
        sec: 60,
        timer: null,
      },

    };
  },
  methods: {
    //获取验证码
    getCode() {
      //对表单的部分字段进行验证
      this.$refs.registerFormRefFirst.validateField("email", async (valid) => {
        if (valid) {
          setTimeout(() => {
            this.$refs.registerFormRefFirst.clearValidate();
          }, 3000);
          return;
        }
        //计时器
        if (this.dataItem.timer) {
          //计时器存在就清除计时器
          clearInterval(this.dataItem.timer);
        }
        //开始计时器
        this.dataItem.timer = setInterval(() => {
          const se = this.dataItem.sec--;
          this.dataItem.button_disabled = true;
          this.dataItem.button_get = `${se}秒`;
          if (se <= 0) {
            clearInterval(this.dataItem.timer);
            this.dataItem.button_disabled = false;
            this.dataItem.button_get = `重新获取`;
          }
        }, 1000);
        
        // 必须传表单
        const result = await getEmailCode(QS.stringify(this.registerForm));
        // 右侧提示消息
        console.log(result)
        if (result.flag) {
          this.$message.success("验证码发送，请稍等")
          this.$notify({
            type: "success",
            title: "发送成功",
            message: h(
              "i",
              { style: "color: teal" },
              "验证码发送成功，请前往邮箱查看"
            ),
          });
        }else{
          this.$notify({
            type: "warning",
            title: "发送失败",
            message: h(
              "i",
              { style: "color: red" },
              "验证码发送失败，请稍后重试"
            ),
          });
        }
        
        const registerEmail = this.registerForm.email;
        if(result.data === registerEmail){
          this.$notify({
          title: '发送失败',
          message: h(
              "i",
              { style: "color: orange" },
              "邮箱【 "+ registerEmail +" 】已存在，请更改邮箱"
            ),
          type: 'warning',
          position: 'top-left'
        });
        }
        

      });
    },

    //第一次下一步
    stepNextFirst() {
      this.$refs.registerFormRefFirst.validate(async (valid) => {
        if (!valid) {
          //3秒后清除提示的错误信息
          setTimeout(() => {
            this.$refs.registerFormRefFirst.clearValidate();
          }, 3000);
          return;
        }

        // 第一步提交邮箱和验证码
        this.loading = true;
        const result = await checkEmailAndCode(QS.stringify(this.registerForm));
        // console.log(result);
        if (result.flag) {
          setTimeout(() => {
            this.loading = false;
            this.step.title1 = "已完成";
            this.step.active = 1;
            this.stepDivFirst = false;

            this.step.title2 = "进行中";
            this.stepDivSecond = true;
          }, 2000);
        }else if(!result.flag){
          this.$message.Error("验证码错误")
        } 
        else {
          this.$message.warning("服务器出问题了，请稍后重试");
        }

      });
    },
    //第二次下一步
    stepNextSecond() {
      this.$refs.registerFormRefSecond.validate(async (valid) => {
        if(!valid){
            setTimeout(() => {
              this.$refs.registerFormRefSecond.clearValidate();
            }, 3000);
          return;
        }
        //提交注册
        const result = await register(this.registerForm)
        // console.log(result)
          setTimeout(() => {
            if(result.code == 200){
              this.loading = true;
              this.$notify({
              title: '注册成功',
              message: h(
                  "i",
                  { style: "color: teal" },
                  "注册成功，前往登录"
                ),
              type: 'success',
              position: 'top-right'
            });
            }
            this.step.title2 = "已完成";
            this.step.active = 2;
            this.stepDivSecond = false;

            this.step.title3 = "进行中";
            this.stepDivThird = true;
            this.dialogVisible = true;
            return;
          }, 2000);
        const registerUsername = this.registerForm.username;
        // console.log(registerUsername)
        if(result.data === registerUsername){
          this.$notify({
          title: '注册失败',
          message: h(
              "i",
              { style: "color: orange" },
              "账号【 "+registerUsername+" 】已存在,请重新输入"
            ),
          type: 'warning',
          position: 'top-left'
        });
        }else{
          this.$message.warning("操作失败，请稍后重试")
        }
      })
      
    },
    //第三次下一步
    stepNextThird() {
      router.push("/Login");
    },
    //初始化的步骤条状态
    stepInit() {
      this.step.title1 = "进行中";
      this.step.active = 0;
      this.step.title2 = "步骤二";
      this.step.title3 = "步骤三";
    },
    //对话框
    handleClose(done) {
      this.$confirm("确认关闭?")
        .then((_) => {
          done();
          this.$notify({
            title: "已关闭",
            message: "可以点击按钮去登录",
            type: "success",
          });
        })
        .catch((_) => {});
    },

    trueButton() {
      this.dialogVisible = false;
      router.push("/Login");
    },
    falseButton() {
      this.dialogVisible = false;
      this.$notify.info({
        title: "提示",
        message: "点击按钮去登陆",
      });
    },
  },

  created() {
    this.stepInit();
  },
};
</script>

<style lang="less" scoped>
#poster {
  height: 100%;
  width: 100%;
  position: relative;
  margin: 0px;
  padding: 0px;
}
.registe_step {
  margin: auto;
  margin-top: 100px;
  width: 70%;
}
.registe_container {
  border-radius: 30px;
  height: 300px;
  width: 400px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}
.step_first {
  padding-top: 100px;
  margin: auto;
  width: 450px;
}
.step_second {
  padding-top: 100px;
  margin: auto;
  width: 450px;
  height: 450px;
}
.step_third {
  // border: red solid;
  margin-top: 100px;
  text-align: center;
}

.registe_title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.next_button_first {
  margin-top: 20px;
  width: 100%;
  // background-color: #505458;
  border: none;
  box-shadow: 0 0 25px #cac6c6;
}
.next_button_second {
  width: 100%;
  border: none;
  box-shadow: 0 0 25px #cac6c6;
}
</style>